<template>
  <div>
    <el-form style="margin-bottom: 15px;">
      <el-button type="primary" @click="getData">查询</el-button>
      <el-button type="success" @click="add">新增</el-button>
      <el-button type="danger" @click="deleteHandle" :disabled="ids.length<=0">批量删除</el-button>
      <el-button type="success" plain round @click="exportData">导出</el-button>
      <el-upload action="http://localhost:8080/user/importData" :headers="{token:loginUser.token}"
                 :show-file-list="false" :on-success="handleImportSuccess" style="display: inline-block;">
        <el-button type="primary" plain round>导入</el-button>
      </el-upload>
    </el-form>
    <el-card style="margin-bottom: 10px">
      <el-table :data="users" show-summary @selection-change="selectionChangeHandle">
        <el-table-column type="selection"></el-table-column>
        <el-table-column type="index" label="序号"></el-table-column>
        <el-table-column label="ID" prop="id" sortable align="center"></el-table-column>
        <el-table-column label="头像" align="center">
          <template v-slot="scope">
            <el-upload
                action="http://localhost:8080/file/upload"
                :headers="{token:loginUser.token}"
                :show-file-list="false"
                :on-success="(row,file)=>handleAvatarSuccess(scope.row,file)"
                :before-upload="beforeAvatarUpload">

              <i v-if="!scope.row.avatar" class="el-icon-plus avatar-uploader-icon"></i>
            </el-upload>
            <el-image v-if="scope.row.avatar" :src="scope.row.avatar" :preview-src-list="[scope.row.avatar]"
                      style="width: 50px; height: 50px; border-radius: 50%;"></el-image>

          </template>
        </el-table-column>
        <el-table-column label="用户名" prop="username" align="center"></el-table-column>
        <el-table-column label="姓名" prop="name" align="center"></el-table-column>
        <el-table-column
            label="地址" prop="address" align="center" :filter-method="filterAddress"
            :filters="[{text: '广东',value:'广东'},{text: '湖南',value: '湖南'}]">
        </el-table-column>
        <el-table-column label="操作" align="center">
          <template v-slot="scope">
            <el-button size="mini" type="primary" @click="edit(scope.row.id)">编辑</el-button>
            <el-button size="mini" type="danger" @click="deleteHandle(scope.row.id)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <el-card>
      <div slot="header" class="clearfix">
        <span>文件上传下载</span>
      </div>
      <div>
        <el-upload
            accept="jpg"
            action="http://localhost:8080/file/upload"
            :headers="{token:loginUser.token}"
            list-type="picture"
            :before-upload="beforeUpload">
          <el-button size="small" type="primary">点击上传</el-button>
          <div slot="tip" class="el-upload__tip">只能上传jpg/png文件，且不超过2MB</div>
        </el-upload>
      </div>
    </el-card>
  </div>
</template>

<script>
import {defineComponent} from 'vue'
import request from "@/utils/request";

export default defineComponent({
  name: "UserView",
  data() {
    return {
      users: [],
      loginUser: {},
      ids: [],
      //新增或修改表单
      formData: {},
    }
  },
  //vue实例创建后，还没渲染数据时，自动执行的操作
  created() {
  },
  //页面完成渲染后自动执行的操作
  mounted() {
    //获取用户列表
    this.getData()
    //获取当前登录用户
    this.loginUser = JSON.parse(localStorage.getItem("user") || '{}')
  },
  methods: {
    //导出数据
    exportData() {
      let url = 'http://localhost:8080/user/export?token=' + this.loginUser.token
      if (this.ids.length !== 0) {
        url += '&ids=' + this.ids
      }
      window.open(url)
    },
    //筛选地址
    filterAddress(value, row) {
      return row.address === value
    },
    //表格选择得到id
    selectionChangeHandle(val) {
      this.ids = val.map(item => item.id)
    },
    //获取列表数据
    getData() {
      request.get('/user/selectAll').then(res => {
        if (res.code === '200')
          this.users = res.data
        else
          this.$message.error(res.msg)
      })
    },
    //新增用户
    add() {
      request.post('/user/add', this.formData).then(res => {
        if (res.code === '200') {
          this.$message.success('新增成功')
          this.getData()
        } else {
          this.$message.error(res.msg)
        }
      })
    },
    //删除用户
    deleteHandle(id) {
      this.$confirm('是否删除' + (id ? id : this.ids) + '号用户？', '删除', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        request({
          url: '/user/delete' + (id ? '/' + id : 'Batch'),
          method: 'delete',
          data: id ? null : this.ids,
        }).then(res => {
          if (res.code === '200') {
            this.$message.success('删除成功')
            this.getData()
          } else {
            this.$message.error(res.msg)
          }
        })
      }).catch(()=>{})
    },
    //修改用户
    edit(id){
      this.$message.info('修改'+id)
      // request.put('/user/update',)
    },
    //头像上传前检查
    beforeAvatarUpload(file) {
      const isJPG = file.type === 'image/jpeg';
      const isLt2M = file.size / 1024 / 1024 < 2;

      if (!isJPG) {
        this.$message.error('上传头像图片只能是 JPG 格式!');
      }
      if (!isLt2M) {
        this.$message.error('上传头像图片大小不能超过 2MB!');
      }
      return isJPG && isLt2M;
    },
    //头像上传成功后操作
    handleAvatarSuccess(row, file) {
      row.avatar = file.response.data
      request.put('/user/update', row).then(res => {
        if (res.code === '200')
          this.$message.success("上传成功")
        else
          this.$message.error(res.msg)
      })
    },
    //导入成功后
    handleImportSuccess(res) {
      console.log(res)
      if (res.code === '200') {
        this.$message.success('导入成功')
      } else if (res.code === '401') {
        this.$message.error(res.msg)
        this.$router.push('/login')
      } else {
        this.$message.error(res.msg)
      }
    },
    //头像上传前操作
    beforeUpload(file) {
      const isJPG = file.type === 'image/jpeg';
      const isLt2M = file.size / 1024 / 1024 < 2;

      if (!isJPG) {
        this.$message.error('上传头像图片只能是 JPG 格式!');
      }
      if (!isLt2M) {
        this.$message.error('上传头像图片大小不能超过 2MB!');
      }
      return isJPG && isLt2M;
    },
    // handleFileUpload(response,file,fileList){
    //     console.log(fileList)
    //     // fileList.add({name:file.name,url:response.data.url})
    //     // this.fileList=fileList
    // },
  }
})
</script>

<style scoped>
</style>
